package com.scau.clothes.netty;

import com.scau.clothes.utils.SpringContextUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MyTextWebSocketFrameHandler extends ChannelInboundHandlerAdapter {

    private static ConcurrentHashMap<String, Channel> map = new ConcurrentHashMap<>();
    private static final String CHAT = "CHAT";
    private StringRedisTemplate redisTemplate = ((StringRedisTemplate) SpringContextUtil.getBean("stringRedisTemplate"));

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (null != msg && msg instanceof FullHttpRequest) {
            handlerConnect(ctx,(FullHttpRequest) msg);
        }else if(msg instanceof TextWebSocketFrame){
            System.out.println("send");
            sendMsg((TextWebSocketFrame) msg);
        }
        super.channelRead(ctx, msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
        ctx.writeAndFlush("出现错误！！！");
        ctx.channel().close();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
    }

    private void sendMsg(TextWebSocketFrame msg){
        String chatKey = "";
        String text = msg.text();
        String[] split = text.split(":");
        if(split.length!=3){
            throw new RuntimeException("格式错误");
        }
        String from = split[0];
        String to = split[1];
        String txt = split[2];
        Channel channel = map.get(to);
        String message = from+":"+txt;
        if (channel != null)
            channel.writeAndFlush(new TextWebSocketFrame("from:"+message));
        if(redisTemplate.hasKey(CHAT+to+from))
            chatKey = CHAT+to+from;
        else
            chatKey = CHAT+from+to;
        redisTemplate.opsForList().leftPush(chatKey,message);
    }
    private void handlerConnect(ChannelHandlerContext ctx,FullHttpRequest msg){
        FullHttpRequest request = (FullHttpRequest) msg;
        String uri = request.uri();
        Map info = getParams(uri);
        String from = (String) info.get("from");
        map.put(from,ctx.channel());
        //如果url包含参数，需要处理
        if(uri.contains("?")){
            String newUri = uri.substring(0, uri.indexOf("?"));
            request.setUri(newUri);
        }
        System.out.println(map);
    }
    private static Map getParams(String uri){
        HashMap<String, String> map = new HashMap<>();
        String resStr = uri.substring(uri.indexOf("?")+1);
        String[] split = resStr.split("&");
        for (String s : split) {
            String[] split1 = s.split("=");
            map.put(split1[0],split1[1]);
        }
        return map;
    }
}
